{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "ename": "Exception",
     "evalue": "抱歉，您没有访问该接口的权限，权限的具体详情访问：https://tushare.pro/document/1?doc_id=108。",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mException\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-3-2ad86cd9eea6>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     13\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     14\u001b[0m \u001b[0mpro\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mts\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpro_api\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'c0cad8f56caba4e70702d606290d04f88514a6bef046f60d13144151'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 15\u001b[1;33m \u001b[0mdf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpro\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfut_holding\u001b[0m\u001b[1;33m(\u001b[0m \u001b[0msymbol\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'JD2008'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mexchange\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'DCE'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     16\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msort_values\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'trade_date'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mascending\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     17\u001b[0m \u001b[0mdf2\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfillna\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32md:\\Anaconda3\\lib\\site-packages\\tushare\\pro\\client.py\u001b[0m in \u001b[0;36mquery\u001b[1;34m(self, api_name, fields, **kwargs)\u001b[0m\n\u001b[0;32m     42\u001b[0m             \u001b[0mresult\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mjson\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mloads\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mres\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtext\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     43\u001b[0m             \u001b[1;32mif\u001b[0m \u001b[0mresult\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'code'\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m!=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 44\u001b[1;33m                 \u001b[1;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'msg'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     45\u001b[0m             \u001b[0mdata\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mresult\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'data'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     46\u001b[0m             \u001b[0mcolumns\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mdata\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'fields'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mException\u001b[0m: 抱歉，您没有访问该接口的权限，权限的具体详情访问：https://tushare.pro/document/1?doc_id=108。"
     ]
    }
   ],
   "source": [
    "# encoding: utf-8\n",
    "import pandas as pd\n",
    "from pandas import *\n",
    "import numpy as np\n",
    "from pymongo import MongoClient\n",
    "import tushare as ts\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "pd.set_option('display.width', None)  # 设置字符显示宽度\n",
    "pd.set_option('display.max_rows', None)  # 设置显示最大行\n",
    "pd.set_option('display.max_columns', None)  # 设置显示最大行\n",
    "\n",
    "pro = ts.pro_api('c0cad8f56caba4e70702d606290d04f88514a6bef046f60d13144151')\n",
    "df = pro.fut_holding( symbol='JD2008', exchange='DCE')\n",
    "df=df.sort_values(['trade_date'],ascending=True)\n",
    "df2=df.fillna(0)\n",
    "jd=df2.loc[df2['broker']!='期货公司会员']\n",
    "jd=jd.copy()\n",
    "broker2=['宏源期货','方正中期','英大期货','格林大华','美尔雅期货']\n",
    "jd['净持仓']=jd.apply(lambda x: x['long_hld'] - x['short_hld'], axis=1)\n",
    "jd=jd[jd['trade_date']>='20200515']\n",
    "jd.tail()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# sums =jd[['trade_date', 'symbol','broker','净持仓']]\n",
    "net_position =jd.groupby(['trade_date', 'symbol'])['净持仓'].sum().reset_index(name='净空汇总')\n",
    "sums = jd.copy()\n",
    "# sums = sums[sums['symbol']=='JD2005']\n",
    "times = sums[sums['trade_date']==sums['trade_date'].iloc[-1]]\n",
    "# print(times)\n",
    "brokers=times['broker']\n",
    "df=pd.DataFrame()\n",
    "for i in brokers:\n",
    "    broker=[sums[sums['broker']==i]]\n",
    "    df = df.append(broker)\n",
    "    \n",
    "df['净持仓变动量'] = df['净持仓'] - df['净持仓'].shift(1).fillna(0)\n",
    "# print(df)\n",
    "df= df[df['trade_date']==df['trade_date'].iloc[-1]]\n",
    "sums = df.sort_values('净持仓')\n",
    "sums = sums[sums['净持仓']!=0]\n",
    "sums =sums[['trade_date', 'symbol','broker','净持仓','净持仓变动量']]\n",
    "sums"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "jd2=jd[jd['净持仓']<0]\n",
    "sums =jd2.groupby(['trade_date', 'symbol'])['净持仓'].sum().reset_index(name='净空汇总')\n",
    "\n",
    "df=pd.DataFrame()\n",
    "for i in broker2:\n",
    "    try:\n",
    "        brokers = jd[jd['broker'] == i]\n",
    "        df2=pd.DataFrame(brokers)\n",
    "        df = df.append(df2)\n",
    "    except:\n",
    "        pass\n",
    "sums2 = df.groupby(['trade_date', 'symbol'])['净持仓'].sum().reset_index(name='五少净空')\n",
    "merge = pd.merge(sums2, sums, on=['trade_date', 'symbol'], how='outer').fillna(0)\n",
    "merge['五少占比']=merge.apply(lambda x: x['五少净空']/x['净空汇总'], axis=1)\n",
    "# merge=merge[merge['symbol']=='JD2005']\n",
    "merge"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "#二行即可搞定画图中文乱码\n",
    "plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\n",
    "plt.rcParams['axes.unicode_minus']=False #用来正常显示负号\n",
    "from IPython.core.display import display, HTML\n",
    "display(HTML(\"<style>.container { width:100% !important; }</style>\"))\n",
    "# 画图\n",
    "plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\n",
    "plt.rcParams['axes.unicode_minus']=False #用来正常显示负号\n",
    "\n",
    "a= pd.DataFrame({'五少占比':np.array(merge['五少占比']),'五少净空':np.array(merge['五少净空'])},index=merge['trade_date'])\n",
    "ax = a.plot(\n",
    "    secondary_y=['五少净空'],\n",
    "    x_compat=True,\n",
    "    grid=True)\n",
    "\n",
    "ax.set_title(merge['symbol'].iloc[0]+\" 五少 \"+str(int(merge['五少净空'].iloc[-1]))+\"手 日期:\"+ merge['trade_date'].iloc[-1] )\n",
    "ax.set_ylabel('占比')\n",
    "ax.grid(linestyle=\"--\", alpha=0.3)\n",
    "\n",
    "ax.right_ax.set_ylabel('净空')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
